package com.lcj.aoch.rule.service.impl;

import java.math.BigDecimal;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.lcj.aoch.rule.config.ConstantConfiguration;
import com.lcj.common.exception.AochException;
import com.lcj.aoch.rule.db.dao.ChargeRuleDao;
import com.lcj.aoch.rule.db.pojo.ChargeRuleEntity;
import com.lcj.aoch.rule.service.ChargeRuleService;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;

import java.util.HashMap;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ChargeRuleServiceImpl implements ChargeRuleService {
  private static final Logger log = LoggerFactory.getLogger(com.lcj.aoch.rule.service.impl.ChargeRuleServiceImpl.class);
  
  @Resource
  private ChargeRuleDao chargeRuleDao;

  @Resource
  private ConstantConfiguration constantConfiguration;
  
  public HashMap searchChargeRuleById(long ruleId) {
    return chargeRuleDao.searchChargeRuleById(ruleId);
  }
  
  @Transactional
  @LcnTransaction
  public int insert(ChargeRuleEntity chargeRuleEntity) {
    chargeRuleEntity.setKey(constantConfiguration.getAesKey());
    return chargeRuleDao.insert(chargeRuleEntity);
  }
  
  public HashMap calculateOrderCharge(String mileage, String time, int minute, String msg) {
    ChargeRuleEntity chargeRuleEntity = chargeRuleDao.searchCurrentRule(msg);
    String rule = chargeRuleEntity.getRule();
    log.info("预估费用规则:\n{}",rule);
    ExpressRunner expressRunner = new ExpressRunner();
    DefaultContext defaultContext = new DefaultContext();
    defaultContext.put("mileage", mileage);
    defaultContext.put("time", time);
    defaultContext.put("minute", Integer.valueOf(minute));
    try {
      HashMap<String, Long> hashMap = (HashMap)expressRunner.execute(rule, (IExpressContext)defaultContext, null, true, false);
      hashMap.put("chargeRuleId", chargeRuleEntity.getId());
      return hashMap;
    } catch (Exception e) {
      log.error("计算代驾费用失败", e);
      throw new AochException("计算代驾费用失败");
    } 
  }

}
